package com.community.zhihuishequ.view.monitor;

import android.content.Context;
import android.os.Looper;
import android.view.SurfaceView;

import com.community.zhihuishequ.R;
import com.community.zhihuishequ.component.CommunityApplication;
import com.community.zhihuishequ.third.HikInterface;
import com.community.zhihuishequ.third.hik.widget.CustomSurfaceView;
import com.community.zhihuishequ.utils.thread.ThreadPoolManager;
import com.community.zhihuishequ.utils.thread.ThreadPoolTask;
import com.community.zhihuishequ.widget.recyclertreeview.TreeNode;
import com.hikvision.sdk.VMSNetSDK;
import com.hikvision.sdk.consts.SDKConstant;
import com.hikvision.sdk.net.bean.CustomRect;
import com.hikvision.sdk.net.bean.LoginData;
import com.hikvision.sdk.net.bean.RootCtrlCenter;
import com.hikvision.sdk.net.bean.SubResourceNodeBean;
import com.hikvision.sdk.net.bean.SubResourceParam;
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness;
import com.hikvision.sdk.utils.FileUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

/**
 * Created by Rick on 17/11/23.
 *
 */

public class MonitorController {

    private static volatile MonitorController instance;

    public static MonitorController getInstance() {
        if (instance == null) {
            synchronized (MonitorController.class) {
                if (instance == null) {
                    instance = new MonitorController();
                }
            }
        }
        return instance;
    }

    private MonitorController() {
    }

    public void init() {
        HikInterface.init();
    }

    public void unInit() {
        HikInterface.unInit();
    }

    public void login() {
        HikInterface.login(new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
                EventBus.getDefault().post(new MonitorToastEvent("连接视频服务器有些问题，麻烦您稍后再试一下！"));
            }

            @Override
            public void onSuccess(Object obj) {
                super.onSuccess(obj);
                if (!(obj instanceof LoginData)) {
                    EventBus.getDefault().post(new MonitorToastEvent("登录出现问题了，麻烦您稍后再试一下！"));
                    return;
                }
                getRootControlCenter();
            }
        });
    }

    private void getRootControlCenter() {
        HikInterface.getRootControlCenter(new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
                EventBus.getDefault().post(new MonitorToastEvent("获取主组织架构错，麻烦您稍后再试一下！"));
            }

            @Override
            public void onSuccess(Object obj) {
                super.onSuccess(obj);
                if (obj instanceof RootCtrlCenter) {
                    RootCtrlCenter center = ((RootCtrlCenter) obj);
                    int nodeType = Integer.parseInt(center.getNodeType());
                    int id = center.getId();
                    getSubResourceList(null, nodeType, id);
                }
            }
        });
    }

    public void getSubResourceList(final TreeNode uiNode, int parentNodeType, int pId) {
        HikInterface.getSubResourceList(parentNodeType, pId, new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
                EventBus.getDefault().post(new MonitorToastEvent("获取子组织架构错，麻烦您稍后再试一下！"));
            }

            @Override
            public void onSuccess(Object obj) {super.onSuccess(obj);
                if (obj instanceof SubResourceParam) {
                    List<SubResourceNodeBean> list = ((SubResourceParam) obj).getNodeList();
                    if (list != null) {
                        EventBus.getDefault().post(new MonitorListEvent(uiNode, list));
                    } else {
                        EventBus.getDefault().post(new MonitorToastEvent("获取子组织内容出错，麻烦您稍后再试一下！"));
                    }
                }
            }
        });
    }

    public void doStartLive(final int winId, final SubResourceNodeBean node, final SurfaceView sv, final int videoQuality, final OnVMSNetSDKBusiness outCallback) {
        // TODO 注意判断是否在线   node.getIsOnline() == 1;
        if (!HikInterface.checkLivePermission(node)) {
            EventBus.getDefault().post(new MonitorToastEvent("没有权限去看这个视频监控，请联系管理员添加权限！"));
            return;
        }
        if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
            doLocalStartLive(winId, node, sv, videoQuality, outCallback);
        } else {
            ThreadPoolTask<Void> task = new ThreadPoolTask<Void>("MonitorActivity-doStartLastLive") {
                @Override
                public void doTask(Void parameter) {
                    doLocalStartLive(winId, node, sv, videoQuality, outCallback);
                }
            };
            ThreadPoolManager.postLongTask(task);
        }
    }

    private void doLocalStartLive(int winId, SubResourceNodeBean node, SurfaceView sv, int videoQuality, final OnVMSNetSDKBusiness outCallback) {
        // TODO 注意判断是否在线   node.getIsOnline() == 1;
        if (!HikInterface.checkLivePermission(node)) {
            EventBus.getDefault().post(new MonitorToastEvent("没有权限去看这个视频监控，请联系管理员添加权限！"));
            return;
        }
        Looper.prepare();
        HikInterface.startLive(winId, node, sv, videoQuality, new OnVMSNetSDKBusiness() {
            @Override
            public void onFailure() {
                super.onFailure();
                EventBus.getDefault().post(new MonitorToastEvent("播放视频监控失败，请重新再试一次！"));
                if (outCallback != null) {
                    outCallback.onFailure();
                }
            }

            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                if (outCallback != null) {
                    outCallback.onSuccess(o);
                }
            }
        });
        Looper.loop();
    }

    public void doStopLive(int winId) {
        boolean stopLiveResult = VMSNetSDK.getInstance().stopLiveOpt(winId);
    }

    public void screenshot(int winId) {
        Context context = CommunityApplication.getContext();
        int opt = VMSNetSDK.getInstance().captureLiveOpt(winId, FileUtils.getPictureDirPath().getAbsolutePath(), "Picture" + System.currentTimeMillis() + ".jpg");
        String msg = null;
        switch (opt) {
            case SDKConstant.LiveSDKConstant.SD_CARD_UN_USABLE:
                msg = context.getString(R.string.monitor_screenshot_sd_card_fail);
                break;
            case SDKConstant.LiveSDKConstant.SD_CARD_SIZE_NOT_ENOUGH:
                msg = context.getString(R.string.monitor_screenshot_sd_card_not_enough);
                break;
            case SDKConstant.LiveSDKConstant.CAPTURE_FAILED:
                msg = context.getString(R.string.monitor_screenshot_fail);
                break;
            case SDKConstant.LiveSDKConstant.CAPTURE_SUCCESS:
                msg = context.getString(R.string.monitor_screenshot_success);
                break;
        }
        if (msg != null) {
            EventBus.getDefault().post(new MonitorToastEvent(msg));
        }
    }

    public void mute(int winId, boolean isMute) {
        Context context = CommunityApplication.getContext();
        //音频按钮点击操作
        String msg = null;
        boolean ret;
        if (isMute) {
            ret = VMSNetSDK.getInstance().stopLiveAudioOpt(winId);
            if (ret) {
                msg = context.getString(R.string.monitor_mute_stop_sound);
            }
        } else {
            ret = VMSNetSDK.getInstance().startLiveAudioOpt(winId);
            if (!ret) {
                msg = context.getString(R.string.monitor_mute_start_sound_fail);
            } else {
                // 开启音频成功，并不代表一定有声音，需要设备开启声音。
                msg = context.getString(R.string.monitor_mute_start_sound_success);
            }
        }
        if (msg != null) {
            EventBus.getDefault().post(new MonitorToastEvent(msg));
        }
    }

    //电子放大选中事件
    public void zoom(final int winId, boolean isZoom, CustomSurfaceView sv) {
        if (isZoom) {
//            sv.scale(2.0f);
//            CustomRect original = sv.getOriginalRect();
//            CustomRect virtual = sv.getVirtualRect();

            sv.setOnZoomListener(new CustomSurfaceView.OnZoomListener() {
                @Override
                public void onZoomChange(CustomRect original, CustomRect current) {
                    VMSNetSDK.getInstance().zoomLiveOpt(winId, true, original, current);
                }
            });
        } else {
            sv.setOnZoomListener(null);
            VMSNetSDK.getInstance().zoomLiveOpt(winId, false, null, null);
        }
    }

}
